package com.selex.display.FirstTest;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Hw808
 */
import ivef.Parser;
import ivef.ParserListener;
import java.io.*;
import java.net.*;

public class Server extends Thread {

    private ServerSocket Server;

    public static void main(String argv[]) throws Exception {
        new Server();
    }

    public Server() throws Exception {
        Server = new ServerSocket(4000);
        System.out.println("Il Server è in attesa sulla porta 4000.");
        this.start();
    }

    public void run() {
        while (true) {
            try {
                System.out.println("In attesa di Connessione.");
                Socket client = Server.accept();
                System.out.println("Connessione accettata da: " + client.getInetAddress());
                Connect c = new Connect(client);
            } catch (Exception e) {
            }
        }
    }
}

class Connect extends Thread {

    private Socket client = null;
    BufferedReader in = null;
    PrintStream out = null;

    public Connect() {
    }

    public Connect(Socket clientSocket) {
        client = clientSocket;
        try {
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));

            out = new PrintStream(client.getOutputStream(), true);
        } catch (Exception e1) {
            try {
                client.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            return;
        }
        this.start();
    }

    public void run() {
        try {

            //XML IVEF
            /**/
             
             
            String tmp, msg = "";
            while ((tmp = in.readLine()) != null) {
                msg =msg+ tmp;
            }

            ParserListener pListener = new PingHandler();
            Parser par = new Parser(pListener);
            boolean result = par.parseXMLString(msg, false);
            /**/

            /**/ 
            out.println("<MSG_IVEF>\n" +
             "<Header MsgRefId=\"1234567890123456789012345678901234567\" Version=\"1.2\"/>\n" +
             "<Body>\n" +
             "<Pong />\n" +
             "</Body>\n" +
             "</MSG_IVEF>");
            /* */
            out.flush();
            // chiude gli stream e le connessioni
            out.close();
            in.close();

            client.close();
        } catch (Exception e) {
        }
    }

}
